<?php
            
use app\model\Util; 
use app\model\Theme; 


/**
 * Desc:
 * Time: 2021/3/12 1:15 下午
 */
class Index_Page extends PluginWebPage {
    
    static $mulit_prize_lt_module_name = 'ew68743';

    //未中奖奖项名称
 static   $notLottery  = [
                ['title'=>'谢谢参与','small_img'=>  'http://img2020.yixuansoft.cn/images/2/2023/10/SKno2GqGQdKHguOSWW2S3mwW3msK2H.png'],
                ['title'=>'未中奖','small_img'=>  'http://img2020.yixuansoft.cn/images/2/2023/10/SKno2GqGQdKHguOSWW2S3mwW3msK2H.png'],
                ['title'=>'再接再厉','small_img'=>  'http://img2020.yixuansoft.cn/images/2/2023/10/SKno2GqGQdKHguOSWW2S3mwW3msK2H.png']
         ];

    function main($method)
    {
        $method = 'lottery_main';
        global $_G,$_P,$_S,$_C;
        $system = $_S;
        $config = $_C;
        $themeid = intval($_P['themeid']);
        if($themeid <= 0){
            $themeid = Theme::getDefaultThemenew();
        }
        $themelist = Theme::getAllTheme();
        $page_index = max(1,intval($_P['page']));
        $page_size = 50;
        $page_start = ($page_index-1)*$page_size;
        $title = isset($_P['title'])?$_P['title']:'';
        $type = isset($_P['type'])?$_P['type']:'';
        $default_type = isset($_P['default_type'])?$_P['default_type']:0;

        $default_type_list = $this->getTypeList($themeid,'default_type',$_C);
        $type_list = $this->getTypeList($themeid,'type',$_C);
        $status_list = $this->getTypeList($themeid,'status',$_C);
        $status = isset($_P['status'])?$_P['status']:0;
        $is_double = $_C['yx_lt_double_flag'];

        $theme = Theme::getThemeById($themeid);
        $end_time = $theme['endtime'];
        $total_show_pr = LotteryModel::getTotalShowPr($themeid);
        $prize_arr = LotteryModel::getPrizeFlagCount($themeid);

        $has_big_prize_count = true;
        $yx_lt_chance_limit = $config['yx_lt_chance_limit'];
        if ($is_double){
            LotteryModel::updateAllPrize(['themeid'=>$themeid],['is_double'=>1]);
        }else{
            LotteryModel::updateAllPrize(['themeid'=>$themeid],['is_double'=>0]);

            $big_prize_count = LotteryModel::getBigQtyPrizeCount($themeid);
            if ($big_prize_count<$config['yx_lt_chance_limit']){
                $has_big_prize_count=false;
            }
        }
        $open_send_redpackage = true;
        if (!$system['fenxiao'] || !$config['yx_lt_open_red_package']){
            $open_send_redpackage = false;
            //禁用红包后  将所有的红包奖品设置为下架状态
            LotteryModel::updateAllPrize(['themeid'=>$themeid,'type'=>'red_envelope'],['status'=>2]);
        }
        //判断数据表是否存在
        if (!db_tableexists(yx_lt_prize)){
            require_once get_path('plugin/lottery/core/install.php');
        }


        $double_num = LotteryModel::getDoublePrizeCount($themeid);
        $lists = LotteryModel::getPrizeList($themeid,$title,$type,$status,$default_type,0,0);
        $free_list = LotteryModel::getPrizeList($themeid,$title,$type,1,2,0,0);
        $free_count = count($free_list);
        $bizhong_list = LotteryModel::getPrizeList($themeid,$title,$type,$status,3,0,0);
        $bizhoing_count = count($bizhong_list);
        $list = LotteryModel::getPrizeList($themeid,$title,$type,$status,$default_type,$page_start,$page_size);
        $full_lists = LotteryModel::getPrizeList($themeid,$title,$type,1,$default_type,0,0);
        $is_full_pr = LotteryModel::getPrTotal($full_lists);
        $total_day_qty = LotteryModel::getDayOut($full_lists);
        //上架商品总数
        $show_list = LotteryModel::getPrizeList($themeid,$title,$type,1,$default_type,0,0);

        $show_list_total = count($show_list);
        $page_total = $total = count($lists);
        $pager = pagination($page_total,$page_index,$page_size);
        //格式化当前奖项的真实占比以及概率
        if ($bizhoing_count>0){
            $bizhong_prize_pr_total = LotteryModel::getPrTotal($list,'pr','bizhong');
            $notbizhong_prize_pr_total = LotteryModel::getPrTotal($list,'pr','notbizhong');
        }else{
            $prize_pr_total = LotteryModel::getPrTotal($list,'pr');
        }
        $prize_show_pr_total = LotteryModel::getPrTotal($list,'show_pr');
        foreach ($list as $k => $v){
            //重置校验总库存 可用库存 已抽出
            if ($v['qty']+$v['out_qty']!=$v['total_qty']){
                db_update(yx_lt_prize,['total_qty'=>$v['qty']+$v['out_qty']],['themeid'=>$themeid,'p_id'=>$v['p_id']]);
                $list[$k]['total_qty']=$v['qty']+$v['out_qty'];
            }

            if ($bizhoing_count>0){
                if ($v['default_type']==3){
                    //必中奖项单独计算
                    $list[$k]['format_pr'] = number_format($v['pr']/$bizhong_prize_pr_total,2)*100;
                }else{
                    //非必中奖项单独计算
                    $list[$k]['format_pr'] = number_format($v['pr']/$notbizhong_prize_pr_total,2)*100;
                }
            }else{
                $list[$k]['format_pr'] = number_format($v['pr']/$prize_pr_total,2)*100;
            }
            $list[$k]['format_show_pr'] = number_format($v['show_pr']/$prize_show_pr_total,2)*100;
        }
        $is_mult_lt = false;
        if (self::$mulit_prize_lt_module_name==MODULE_NAME || MODULE_NAME=='tp0210' || MODULE_NAME=='yx18900'){
            $is_mult_lt = true;
        }
        $return_clicent = get_defined_vars();
return $this->view('/lottery/index/main', $return_clicent);
    }

    function add()
    {
        return $this->post();
    }

    function edit()
    {
        return $this->post();
    }
    //上传实例模版
    function uploadFile()
    {
        global $_G,$_P,$_S,$_C;
        $themeid = intval($_P['themeid']);
        $all_arr = [];
        $file = $_FILES['file'];
        $filename = $file['tmp_name'];
        if (empty($filename)){
            $response = ['code'=>30000,'msg'=>'请选择要导入的CSV文件！','data'=>[]];
            return_msg($response, '', 'ajax');
        }
        if (!$file['size']){
            $response = ['code'=>30000,'msg'=>'文件不能为空！','data'=>[]];
            return_msg($response, '', 'ajax');
        }
        if ($file['name'] && $file['error']==0){
            $type = substr($file['name'],strpos($file['name'],"."));
            $type = strtolower($type);
            if (!in_array($type,['.csv'])){
                $response = ['code'=>30000,'msg'=>'文件类型错误！','data'=>[]];
                return_msg($response, '', 'ajax');
            }
        }
        $handle = fopen($file['tmp_name'],'r');
        $out = array ();
        $n = 0;
        while ($data = fgetcsv($handle, 10000))
        {
            $num = count($data);
            for ($i = 0; $i < $num; $i++)
            {
                $out[$n][$i] = $data[$i];
            }
            $n++;
        }
        $result = $out;
        $len_result = count($result);
        if($len_result==0){
            $response = ['code'=>30000,'msg'=>'无数据！','data'=>[]];
            return_msg($response, '', 'ajax');
        }
        $data_values = '';
        for($i = 1; $i < $len_result; $i++) //循环获取各字段值
        {
            $name = trim($result[$i][0]);
            $title = trim($result[$i][1]);
            $desc_content = trim($result[$i][2]);
            $qty = trim($result[$i][3]);
            $total_qty = trim($result[$i][3]);
            $out_qty = 0;
            $day_qty = 0;
            $type = trim($result[$i][4]);
            if ($type=='红包奖品'){
                $type = 'red_envelope';
            }else{
                $type = 'default';
            }
            $pr = trim($result[$i][5]);
            $show_pr = trim($result[$i][6]);
            $red_envelopes_day_qty = trim($result[$i][7]);
            $red_envelopes_amount_min = trim($result[$i][8]);
            $red_envelopes_amount_max = trim($result[$i][9]);
            $show_sort = trim($result[$i][10]);
            $default_type = trim($result[$i][11]);
            if ($default_type=='谢谢参与'){
                $default_type = 2;
            }elseif ($default_type=='必中奖项'){
                $default_type = 3;
            }else{
                $default_type = 1;
            }
            $data_values .= "('$name','$title','$desc_content','$qty','$total_qty','$out_qty','$day_qty',$type','$pr','$show_pr','$red_envelopes_day_qty','$red_envelopes_amount_min','$red_envelopes_amount_max','$show_sort','$default_type','$themeid'),";
        }
        $data_values = substr($data_values,0,-1); //去掉最后一个逗号
        fclose($handle); //关闭指针
        $sql = "INSERT INTO ".tablename(yx_lt_prize)." (`name`, `title`, `desc_content`,`qty`,`total_qty`,`out_qty`,`day_qty`,`type`,`pr`,`show_pr`,`red_envelopes_day_qty`,`red_envelopes_amount_min`,`red_envelopes_amount_max`,`show_sort`,`default_type`,`themeid`) VALUES $data_values";//sql语句
        $res = \think\Db::execute($sql);
        $response = ['code'=>200,'msg'=>'操作成功,请稍后查看！','data'=>[]];
        return_msg($response, '', 'ajax');
    }
    //下载实例模版
    function downLoad()
    {
        global $_G,$_S,$_C,$_P;
        $system = $_S;
        $config = $_C;
        $themeid = $_P['themeid'];
        $temp_list = $this->getDefaultPrizeList($_C,$themeid);


        $count = count($temp_list);
        $pagesize = ceil($count/5000);
        $header = array(
            'name' => '奖项名称', 'title' => '奖品名称', 'desc_content' => '奖品描述',
            'qty' => '库存','type' => '奖品类型', 'pr'=>'中奖概率', 'show_pr' => '中奖记录占比',
            'red_envelopes_day_qty' => '红包每日发放数量','red_envelopes_amount_min' => '红包最小金额', 'red_envelopes_amount_max'=>'红包最大金额', 'show_sort' => '展示排序',
             'default_type'=>'奖品属性',
        );
        $keys = array_keys($header);
        $html = "\xEF\xBB\xBF";
        foreach ($header as $li) {
            $html .= $li . "\t ,";
        }
        $html .= "\n";
//        for ($j = 1; $j <= $pagesize; $j++) {


            $list = $temp_list;

            if (!empty($list)) {
                $size = ceil(count($list) / 500);
                for ($i = 0; $i < $size; $i++) {
                    $buffer = array_slice($list, $i * 500, 500);
                    foreach ($buffer as $row) {
                        switch ($row['type']){
                            case 'default':
                                $row['type']='实物奖品';
                                break;
                            default:
                                $row['type']='红包奖品';
                                break;
                        }
                        switch ($row['default_type']){
                            case 1:
                                $row['default_type'] = '正常奖项';
                                break;
                            case 2:
                                $row['default_type'] = '谢谢参与';
                                break;
                            case 3:
                                $row['default_type'] = '必中奖项';
                                break;
                            default:
                                break;
                        }
                        foreach ($keys as $key) {
                            $data[] = $row[$key];
                        }
                        if (isset($data)){
                            $user[] = implode("\t ,", $data) . "\t ,";
                            unset($data);
                        }
                    }
                    $html .= implode("\n", $user)."\n";
                    unset($user);
                }
//            }
        }
        //新版本导出合并
        Util::WxJump($_S,$html,'示例模版奖品',$themeid,1,1);
    }

    /**
     * Desc:根据配置生成演示案例数据
     * Author:cbw
     * Time: 2023/11/18 14:29
     * @param $_C
     * @param $themeid
     * @return array[]
     */
    function getDefaultPrizeList($_C,$themeid)
    {
        if ($_C['yx_lt_open_red_package']==1){
            if ($_C['yx_lt_double_flag']){
                $temp_list = [
                    ['name'=>'一等奖','title'=>'小黄鸭早餐杯','qty'=>10000,'total_qty'=>10000,'out_qty'=>0,'day_qty'=>0,'type'=>'default','pr'=>5,'show_pr'=>4,'red_envelopes_day_qty'=>0,'red_envelopes_amount_min'=>0,'red_envelopes_amount_max'=>0,'show_sort'=>1,'small_img'=>'http://img2020.yixuansoft.cn/images/2/2023/09/js5hFi7f47rsf772fHfR7WR777h774.jpg/99.jpg','status'=>1,'is_double'=>0,'default_type'=>1,'themeid'=>$themeid],
                    ['name'=>'三等奖','title'=>'吹风机','qty'=>10000,'total_qty'=>10000,'out_qty'=>0,'day_qty'=>0,'type'=>'default','pr'=>10,'show_pr'=>4,'red_envelopes_day_qty'=>0,'red_envelopes_amount_min'=>0,'red_envelopes_amount_max'=>0,'show_sort'=>2,'small_img'=>'http://img2020.yixuansoft.cn/images/2/2021/07/ZB8253B5JgIizgIfXZJsrXg5588RrJ.jpg/99.jpg','status'=>1,'is_double'=>1,'default_type'=>1,'themeid'=>$themeid],
                    ['name'=>'五等奖','title'=>'皮箱','qty'=>10000,'total_qty'=>10000,'out_qty'=>0,'day_qty'=>0,'type'=>'default','pr'=>10,'show_pr'=>4,'red_envelopes_day_qty'=>0,'red_envelopes_amount_min'=>0,'red_envelopes_amount_max'=>0,'show_sort'=>3,'small_img'=>'http://img2020.yixuansoft.cn/images/2/2021/07/F7QFK76hA7mwgKqS7sl82EEg6C7Mgl.jpg/99.jpg','status'=>1,'is_double'=>0,'default_type'=>1,'themeid'=>$themeid],
                    ['name'=>'七等奖','title'=>'彩色画笔','qty'=>10000,'total_qty'=>10000,'out_qty'=>0,'day_qty'=>0,'type'=>'default','pr'=>15,'show_pr'=>4,'red_envelopes_day_qty'=>0,'red_envelopes_amount_min'=>0,'red_envelopes_amount_max'=>0,'show_sort'=>4,'small_img'=>'http://img2020.yixuansoft.cn/images/2/2021/07/UCL3CF9kAv3j25rUlPLv5Aql5qfFKr.jpg/99.jpg','status'=>1,'is_double'=>0,'default_type'=>1,'themeid'=>$themeid],

                    ['name'=>'二等奖','title'=>'红包10元','qty'=>10000,'total_qty'=>10000,'out_qty'=>0,'day_qty'=>0,'type'=>'red_envelope','pr'=>5,'show_pr'=>4,'red_envelopes_day_qty'=>10,'red_envelopes_amount_min'=>10,'red_envelopes_amount_max'=>10,'show_sort'=>5,'small_img'=>'http://img2020.yixuansoft.cn/images/2/2021/08/MG9vfns647ARALN9eYXsX77llrIl0S.png','status'=>1,'is_double'=>1,'default_type'=>1,'themeid'=>$themeid],
                    ['name'=>'四等奖','title'=>'红包5元','qty'=>10000,'total_qty'=>10000,'out_qty'=>0,'day_qty'=>0,'type'=>'red_envelope','pr'=>10,'show_pr'=>4,'red_envelopes_day_qty'=>10,'red_envelopes_amount_min'=>5,'red_envelopes_amount_max'=>5,'show_sort'=>6,'small_img'=>'http://img2020.yixuansoft.cn/images/2/2021/08/MG9vfns647ARALN9eYXsX77llrIl0S.png','status'=>1,'is_double'=>0,'default_type'=>1,'themeid'=>$themeid],
                    ['name'=>'六等奖','title'=>'随机3-4元红包','qty'=>10000,'total_qty'=>10000,'out_qty'=>0,'day_qty'=>0,'type'=>'red_envelope','pr'=>25,'show_pr'=>4,'red_envelopes_day_qty'=>10,'red_envelopes_amount_min'=>3,'red_envelopes_amount_max'=>4,'show_sort'=>8,'small_img'=>'http://img2020.yixuansoft.cn/images/2/2021/08/MG9vfns647ARALN9eYXsX77llrIl0S.png','status'=>1,'is_double'=>1,'default_type'=>1,'themeid'=>$themeid],
                    ['name'=>'八等奖','title'=>'随机1-2元红包','qty'=>10000,'total_qty'=>10000,'out_qty'=>0,'day_qty'=>0,'type'=>'red_envelope','pr'=>20,'show_pr'=>4,'red_envelopes_day_qty'=>10,'red_envelopes_amount_min'=>1,'red_envelopes_amount_max'=>2,'show_sort'=>7,'small_img'=>'http://img2020.yixuansoft.cn/images/2/2021/08/MG9vfns647ARALN9eYXsX77llrIl0S.png','status'=>1,'is_double'=>0,'default_type'=>1,'themeid'=>$themeid],
                ];
            }else{
                $temp_list = [
                    ['name'=>'一等奖','title'=>'懒人沙发','qty'=>10000,'total_qty'=>10000,'out_qty'=>0,'day_qty'=>0,'type'=>'default','pr'=>5,'show_pr'=>4,'red_envelopes_day_qty'=>0,'red_envelopes_amount_min'=>0,'red_envelopes_amount_max'=>0,'show_sort'=>1,'small_img'=>'http://img2020.yixuansoft.cn/images/2/2023/09/FzQNvZBe9GSVaig10Nnj8hQ7QBBqj7.jpg/99.jpg','status'=>1,'is_double'=>0,'default_type'=>1,'themeid'=>$themeid],
                    ['name'=>'三等奖','title'=>'吹风机','qty'=>10000,'total_qty'=>10000,'out_qty'=>0,'day_qty'=>0,'type'=>'default','pr'=>10,'show_pr'=>4,'red_envelopes_day_qty'=>0,'red_envelopes_amount_min'=>0,'red_envelopes_amount_max'=>0,'show_sort'=>2,'small_img'=>'http://img2020.yixuansoft.cn/images/2/2021/07/ZB8253B5JgIizgIfXZJsrXg5588RrJ.jpg/99.jpg','status'=>1,'is_double'=>0,'default_type'=>1,'themeid'=>$themeid],
                    ['name'=>'五等奖','title'=>'皮箱','qty'=>10000,'total_qty'=>10000,'out_qty'=>0,'day_qty'=>0,'type'=>'default','pr'=>10,'show_pr'=>4,'red_envelopes_day_qty'=>0,'red_envelopes_amount_min'=>0,'red_envelopes_amount_max'=>0,'show_sort'=>3,'small_img'=>'http://img2020.yixuansoft.cn/images/2/2021/07/F7QFK76hA7mwgKqS7sl82EEg6C7Mgl.jpg/99.jpg','status'=>1,'is_double'=>0,'default_type'=>1,'themeid'=>$themeid],
                    ['name'=>'七等奖','title'=>'彩色画笔','qty'=>10000,'total_qty'=>10000,'out_qty'=>0,'day_qty'=>0,'type'=>'default','pr'=>15,'show_pr'=>4,'red_envelopes_day_qty'=>0,'red_envelopes_amount_min'=>0,'red_envelopes_amount_max'=>0,'show_sort'=>4,'small_img'=>'http://img2020.yixuansoft.cn/images/2/2021/07/UCL3CF9kAv3j25rUlPLv5Aql5qfFKr.jpg/99.jpg','status'=>1,'is_double'=>0,'default_type'=>1,'themeid'=>$themeid],

                    ['name'=>'二等奖','title'=>'红包10元','qty'=>10000,'total_qty'=>10000,'out_qty'=>0,'day_qty'=>0,'type'=>'red_envelope','pr'=>5,'show_pr'=>4,'red_envelopes_day_qty'=>10,'red_envelopes_amount_min'=>10,'red_envelopes_amount_max'=>10,'show_sort'=>5,'small_img'=>'http://img2020.yixuansoft.cn/images/2/2021/08/MG9vfns647ARALN9eYXsX77llrIl0S.png','status'=>1,'is_double'=>0,'default_type'=>1,'themeid'=>$themeid],
                    ['name'=>'四等奖','title'=>'红包5元','qty'=>10000,'total_qty'=>10000,'out_qty'=>0,'day_qty'=>0,'type'=>'red_envelope','pr'=>10,'show_pr'=>4,'red_envelopes_day_qty'=>10,'red_envelopes_amount_min'=>5,'red_envelopes_amount_max'=>5,'show_sort'=>6,'small_img'=>'http://img2020.yixuansoft.cn/images/2/2021/08/MG9vfns647ARALN9eYXsX77llrIl0S.png','status'=>1,'is_double'=>0,'default_type'=>1,'themeid'=>$themeid],
                    ['name'=>'六等奖','title'=>'随机1-2元红包','qty'=>10000,'total_qty'=>10000,'out_qty'=>0,'day_qty'=>0,'type'=>'red_envelope','pr'=>25,'show_pr'=>4,'red_envelopes_day_qty'=>10,'red_envelopes_amount_min'=>1,'red_envelopes_amount_max'=>2,'show_sort'=>8,'small_img'=>'http://img2020.yixuansoft.cn/images/2/2021/08/MG9vfns647ARALN9eYXsX77llrIl0S.png','status'=>1,'is_double'=>0,'default_type'=>1,'themeid'=>$themeid],
                    ['name'=>'很遗憾','title'=>'谢谢参与','qty'=>999999,'total_qty'=>999999,'out_qty'=>0,'day_qty'=>0,'type'=>'default','pr'=>20,'show_pr'=>4,'red_envelopes_day_qty'=>0,'red_envelopes_amount_min'=>0,'red_envelopes_amount_max'=>0,'show_sort'=>7,'small_img'=>'http://img2020.yixuansoft.cn/images/2/2023/10/SKno2GqGQdKHguOSWW2S3mwW3msK2H.png','status'=>1,'is_double'=>0,'default_type'=>2,'themeid'=>$themeid],
                ];
            }

        }else{
            if ($_C['yx_lt_double_flag']){
                $temp_list = [
                    ['name'=>'一等奖','title'=>'小黄鸭早餐杯','qty'=>10000,'total_qty'=>10000,'out_qty'=>0,'day_qty'=>0,'type'=>'default','pr'=>5,'show_pr'=>4,'red_envelopes_day_qty'=>0,'red_envelopes_amount_min'=>0,'red_envelopes_amount_max'=>0,'show_sort'=>1,'small_img'=>'http://img2020.yixuansoft.cn/images/2/2023/09/js5hFi7f47rsf772fHfR7WR777h774.jpg/99.jpg','status'=>1,'is_double'=>0,'default_type'=>1,'themeid'=>$themeid],
                    ['name'=>'三等奖','title'=>'懒人沙发','qty'=>10000,'total_qty'=>10000,'out_qty'=>0,'day_qty'=>0,'type'=>'default','pr'=>10,'show_pr'=>4,'red_envelopes_day_qty'=>0,'red_envelopes_amount_min'=>0,'red_envelopes_amount_max'=>0,'show_sort'=>2,'small_img'=>'http://img2020.yixuansoft.cn/images/2/2023/09/FzQNvZBe9GSVaig10Nnj8hQ7QBBqj7.jpg/99.jpg','status'=>1,'is_double'=>0,'default_type'=>1,'themeid'=>$themeid],
                    ['name'=>'五等奖','title'=>'电炖锅','qty'=>10000,'total_qty'=>10000,'out_qty'=>0,'day_qty'=>0,'type'=>'default','pr'=>10,'show_pr'=>4,'red_envelopes_day_qty'=>0,'red_envelopes_amount_min'=>0,'red_envelopes_amount_max'=>0,'show_sort'=>3,'small_img'=>'http://img2020.yixuansoft.cn/images/2/2023/09/Mz56y546rh99GR445DRZZYX4z5X3Dh.jpg/99.jpg','status'=>1,'is_double'=>1,'default_type'=>1,'themeid'=>$themeid],
                    ['name'=>'七等奖','title'=>'积木桌','qty'=>10000,'total_qty'=>10000,'out_qty'=>0,'day_qty'=>0,'type'=>'default','pr'=>25,'show_pr'=>4,'red_envelopes_day_qty'=>0,'red_envelopes_amount_min'=>0,'red_envelopes_amount_max'=>0,'show_sort'=>4,'small_img'=>'http://img2020.yixuansoft.cn/images/2/2023/09/R7YOqsNSszrsBhb75Tit9554CVyMMI.png','status'=>1,'is_double'=>0,'default_type'=>1,'themeid'=>$themeid],

                    ['name'=>'二等奖','title'=>'陶泥机','qty'=>10000,'total_qty'=>10000,'out_qty'=>0,'day_qty'=>0,'type'=>'default','pr'=>5,'show_pr'=>4,'red_envelopes_day_qty'=>0,'red_envelopes_amount_min'=>0,'red_envelopes_amount_max'=>0,'show_sort'=>5,'small_img'=>'http://img2020.yixuansoft.cn/images/2/2023/09/c9J1BM1pbTJx5TlKJ1kKfkCX5zkbsM.jpg/99.jpg','status'=>1,'is_double'=>0,'default_type'=>1,'themeid'=>$themeid],
                    ['name'=>'四等奖','title'=>'空气炸锅','qty'=>10000,'total_qty'=>10000,'out_qty'=>0,'day_qty'=>0,'type'=>'default','pr'=>10,'show_pr'=>4,'red_envelopes_day_qty'=>0,'red_envelopes_amount_min'=>0,'red_envelopes_amount_max'=>0,'show_sort'=>6,'small_img'=>'http://img2020.yixuansoft.cn/images/2/2022/08/Ral7AilxstXlsvXiTR1lZTr75aX7bi.jpg/99.jpg','status'=>1,'is_double'=>0,'default_type'=>1,'themeid'=>$themeid],
                    ['name'=>'六等奖','title'=>'网红行李箱','qty'=>10000,'total_qty'=>10000,'out_qty'=>0,'day_qty'=>0,'type'=>'default','pr'=>15,'show_pr'=>4,'red_envelopes_day_qty'=>0,'red_envelopes_amount_min'=>0,'red_envelopes_amount_max'=>0,'show_sort'=>8,'small_img'=>'http://img2020.yixuansoft.cn/images/2/2021/07/F7QFK76hA7mwgKqS7sl82EEg6C7Mgl.jpg/99.jpg','status'=>1,'is_double'=>1,'default_type'=>1,'themeid'=>$themeid],
                    ['name'=>'八等奖','title'=>'彩色画笔','qty'=>10000,'total_qty'=>10000,'out_qty'=>0,'day_qty'=>0,'type'=>'default','pr'=>20,'show_pr'=>4,'red_envelopes_day_qty'=>0,'red_envelopes_amount_min'=>0,'red_envelopes_amount_max'=>0,'show_sort'=>7,'small_img'=>'http://img2020.yixuansoft.cn/images/2/2021/07/UCL3CF9kAv3j25rUlPLv5Aql5qfFKr.jpg/99.jpg','status'=>1,'is_double'=>0,'default_type'=>1,'themeid'=>$themeid],
                ];
            }else{
                $temp_list = [
                    ['name'=>'一等奖','title'=>'懒人沙发','qty'=>10000,'total_qty'=>10000,'out_qty'=>0,'day_qty'=>0,'type'=>'default','pr'=>5,'show_pr'=>4,'red_envelopes_day_qty'=>0,'red_envelopes_amount_min'=>0,'red_envelopes_amount_max'=>0,'show_sort'=>1,'small_img'=>'http://img2020.yixuansoft.cn/images/2/2023/09/FzQNvZBe9GSVaig10Nnj8hQ7QBBqj7.jpg/99.jpg','status'=>1,'is_double'=>0,'default_type'=>1,'themeid'=>$themeid],
                    ['name'=>'三等奖','title'=>'吹风机','qty'=>10000,'total_qty'=>10000,'out_qty'=>0,'day_qty'=>0,'type'=>'default','pr'=>10,'show_pr'=>4,'red_envelopes_day_qty'=>0,'red_envelopes_amount_min'=>0,'red_envelopes_amount_max'=>0,'show_sort'=>2,'small_img'=>'http://img2020.yixuansoft.cn/images/2/2021/07/ZB8253B5JgIizgIfXZJsrXg5588RrJ.jpg/99.jpg','status'=>1,'is_double'=>0,'default_type'=>1,'themeid'=>$themeid],
                    ['name'=>'五等奖','title'=>'积木桌','qty'=>10000,'total_qty'=>10000,'out_qty'=>0,'day_qty'=>0,'type'=>'default','pr'=>10,'show_pr'=>4,'red_envelopes_day_qty'=>0,'red_envelopes_amount_min'=>0,'red_envelopes_amount_max'=>0,'show_sort'=>3,'small_img'=>'http://img2020.yixuansoft.cn/images/2/2023/09/R7YOqsNSszrsBhb75Tit9554CVyMMI.png','status'=>1,'is_double'=>0,'default_type'=>1,'themeid'=>$themeid],
                    ['name'=>'七等奖','title'=>'彩色画笔','qty'=>10000,'total_qty'=>10000,'out_qty'=>0,'day_qty'=>0,'type'=>'default','pr'=>25,'show_pr'=>4,'red_envelopes_day_qty'=>0,'red_envelopes_amount_min'=>0,'red_envelopes_amount_max'=>0,'show_sort'=>4,'small_img'=>'http://img2020.yixuansoft.cn/images/2/2021/07/UCL3CF9kAv3j25rUlPLv5Aql5qfFKr.jpg/99.jpg','status'=>1,'is_double'=>0,'default_type'=>1,'themeid'=>$themeid],

                    ['name'=>'二等奖','title'=>'陶泥机','qty'=>10000,'total_qty'=>10000,'out_qty'=>0,'day_qty'=>0,'type'=>'default','pr'=>5,'show_pr'=>4,'red_envelopes_day_qty'=>0,'red_envelopes_amount_min'=>0,'red_envelopes_amount_max'=>0,'show_sort'=>5,'small_img'=>'http://img2020.yixuansoft.cn/images/2/2023/09/c9J1BM1pbTJx5TlKJ1kKfkCX5zkbsM.jpg/99.jpg','status'=>1,'is_double'=>0,'default_type'=>1,'themeid'=>$themeid],
                    ['name'=>'四等奖','title'=>'便当包','qty'=>10000,'total_qty'=>10000,'out_qty'=>0,'day_qty'=>0,'type'=>'default','pr'=>10,'show_pr'=>4,'red_envelopes_day_qty'=>0,'red_envelopes_amount_min'=>0,'red_envelopes_amount_max'=>0,'show_sort'=>6,'small_img'=>'http://img2020.yixuansoft.cn/images/2/2023/08/MpeerEg5uu80dFkLzJJ85floYJ0l0L.jpg/99.jpg','status'=>1,'is_double'=>0,'default_type'=>1,'themeid'=>$themeid],
                    ['name'=>'六等奖','title'=>'网红行李箱','qty'=>10000,'total_qty'=>10000,'out_qty'=>0,'day_qty'=>0,'type'=>'default','pr'=>15,'show_pr'=>4,'red_envelopes_day_qty'=>0,'red_envelopes_amount_min'=>0,'red_envelopes_amount_max'=>0,'show_sort'=>8,'small_img'=>'http://img2020.yixuansoft.cn/images/2/2021/07/F7QFK76hA7mwgKqS7sl82EEg6C7Mgl.jpg/99.jpg','status'=>1,'is_double'=>0,'default_type'=>1,'themeid'=>$themeid],
                    ['name'=>'很遗憾','title'=>'谢谢参与','qty'=>999999,'total_qty'=>999999,'out_qty'=>0,'day_qty'=>0,'type'=>'default','pr'=>20,'show_pr'=>4,'red_envelopes_day_qty'=>0,'red_envelopes_amount_min'=>0,'red_envelopes_amount_max'=>0,'show_sort'=>7,'small_img'=>'http://img2020.yixuansoft.cn/images/2/2023/10/SKno2GqGQdKHguOSWW2S3mwW3msK2H.png','status'=>1,'is_double'=>0,'default_type'=>2,'themeid'=>$themeid],
                ];
            }
        }
        return $temp_list;
    }

    /**
     * Desc:一键添加示例奖项
     * Author:cbw
     * Time: 2023/11/18 14:28
     */
    function defaultItems()
    {
        global $_G,$_P,$_S,$_C;
        $themeid = intval($_P['themeid']);
        if($themeid <= 0){
            $themeid = Theme::getDefaultThemenew();
        }
        $lists = LotteryModel::getPrizeList($themeid,'','',0,0,0,0);
        if (count($lists)>0){
            show_json(0,['msg'=>'存在奖品数据，无法一键添加']);
        }
        $temp_list = $this->getDefaultPrizeList($_C,$themeid);
        foreach ($temp_list as $key => $val){
            $res = LotteryModel::insertPrize($val);
        }
//        特殊活动临时代码
        if (self::$mulit_prize_lt_module_name && (self::$mulit_prize_lt_module_name==MODULE_NAME  || MODULE_NAME=='tp0210' || MODULE_NAME=='yx18900')){
            foreach ($temp_list as $k => $v){
                $v['status'] =2;
                LotteryModel::insertPrize($v);
            }
        }
        show_json(1,['msg'=>'操作成功']);
    }

    /**
     * Desc:删除奖品
     * Author:cbw
     * Time: 2023/11/18 14:31
     */
    function delete()
    {
        global $_G,$_P,$_S,$_C;
        $system = $_S;
        $config = $_C;
        $p_id = trim($_P['p_id']);
        $themeid = trim($_P['themeid']);
        if ($p_id && $themeid){
            $res = LotteryModel::deletePrize($p_id,$themeid);
            if ($res){
                show_json(1,['msg'=>'操作成功']);
            }else{
                show_json(0,['msg'=>'操作失败']);
            }
        }
    }

    /**
     * Desc:奖品新增或修改
     * Author:cbw
     * Time: 2023/11/18 14:31
     */
    protected function post()
    {
        global $_G,$_S,$_C,$_P;
        $system = $_S;
        $config = $_C;
        $p_id = intval($_P['p_id']);
        $themeid = $_P['themeid'];
        if ($_G['ispost'] && $themeid) {
            $title = trim($_P['title']);
            $name = trim($_P['name']);
            $qty = trim($_P['qty']);
            $day_qty = trim($_P['day_qty']);
            $type = isset($_P['type'])?trim($_P['type']):"default";
            $pr = trim($_P['pr']);
            $show_pr = trim($_P['show_pr']);
            $is_double = $_P['is_double'];
            $desc = strip_tags(htmlspecialchars($_P['desc']));

            if ($title && !$name){
                $name = $title;
            }

            if (empty($title) || !$title){
                show_json(0,['msg'=>'奖品名称不能为空！']);
                die();
            }
            if (empty($name) || !$name){
                show_json(0,['msg'=>'奖项名称不能为空！']);
                die();
            }
            if (mb_strlen($desc,'UTF8')>100){
                show_json(0,['msg'=>'奖品介绍限制100字以内']);
                die();
            }
            $red_envelopes_day_qty = trim($_P['red_envelopes_day_qty']);
            $red_envelopes_amount_min = isset($_P['red_envelopes_amount_min'])?$_P['red_envelopes_amount_min']:0.3;
            $red_envelopes_amount_max = isset($_P['red_envelopes_amount_max'])?$_P['red_envelopes_amount_max']:0.3;
            if ($type=='red_envelope' && $red_envelopes_amount_min<0.3){
                show_json(0,['msg'=>'红包发放金额最小为0.3元']);
                die();
            }
            if ($type=='red_envelope' && $red_envelopes_amount_min>$red_envelopes_amount_max){
                show_json(0,['msg'=>'红包发放金额，最小值不可大于最大值']);
                die();
            }
            if ($type=='red_envelope' && $red_envelopes_amount_max>$_C['red_envelopes_day_amount']){
                show_json(0,['msg'=>'随机金额不可大于每日发放红包总金额']);
                die();
            }
            $show_sort = $_P['show_sort'];
            $small_img = '';
            if($_P['small_img']){
                $small_img = tomedia($_P['small_img']);
            }

            $default_type = $_P['default_type'];
            $themeid = $_P['themeid'];
            $status = $_P['status'];
            if ($_C['yx_lt_open_red_package']==1 && $default_type==3){
                show_json(0,['msg'=>'重复性奖项，不可设置必中奖']);
                die();
            }
            if ($default_type==2){
                if (!$small_img){
                    $small_img = 'https://dpy01cdn.yixuan.net/images/2/2021/04/nfYMpyuxB4Lf90YLcqVujXqMVUf6fP.png';
                }
            }
            if ($type=='red_envelope' && !$small_img){
                $small_img = 'https://dpy01cdn.yixuan.net/images/2/2021/08/upwqCCQ75uEZPoze5WebOAqeNQ5CsJ.png';
            }

            if (!$small_img){
                show_json(0,['msg'=>'奖品未设置图片']);
                die();
            }
            $data = [
                'title'=>$title,
                'name'=>$name,
                'desc_content'=>$desc,
                'total_qty'=>$qty,
                'qty'=>$qty,
                'day_qty'=>$day_qty,
                'type'=>$type,
                'pr'=>$pr,
                'show_pr'=>$show_pr,
                'red_envelopes_day_qty'=>$red_envelopes_day_qty,
                'red_envelopes_amount_min'=>$red_envelopes_amount_min,
                'red_envelopes_amount_max'=>$red_envelopes_amount_max,
                'show_sort'=>$show_sort,
                'small_img'=>$small_img,
                'default_type'=>$default_type,
                'themeid'=>$themeid,
                'is_double'=>$is_double,
                'status'=>$status
            ];


            if (!$p_id){
                $res = LotteryModel::insertPrize($data);
            }else{
                $old_item = LotteryModel::getPrizeItemById($p_id,$themeid);
                $old_item['lottery_title'] = $old_item['title'];
                unset($old_item['title']);
                $old_item['lottery_name'] = $old_item['name'];
                unset($old_item['name']);
                unset($old_item['is_double']);
                unset($old_item['created_at']);
                unset($old_item['updated_at']);
                unset($old_item['out_qty']);
                unset($old_item['p_id']);
                $new_item = $data;
                unset($new_item['is_double']);
                unset($new_item['created_at']);
                unset($new_item['updated_at']);
                $old_item['lottery_title2'] ='';
                $new_item['lottery_title2'] = $new_item['title'];
                $new_item['lottery_title'] = $new_item['title'];
                unset($new_item['title']);
                $new_item['lottery_name'] = $new_item['name'];
                unset($new_item['name']);

                $type = '抽奖奖品编辑';
                writelog($themeid,$type,$old_item,$new_item,$_G['username']);
                $where = ['p_id'=>$p_id,'themeid'=>$themeid];
                $res = LotteryModel::editPrizeItemByWhere($where,$data);
            }
            if (!$res){
                show_json(0,['msg'=>'操作失败']);
            }else{
                show_json(1,['msg'=>'操作成功']);
            }
        }
        if ($p_id && $themeid) {
            $item = LotteryModel::getPrizeItemById($p_id,$themeid);
        }
        $not_lottery =  self::$notLottery;
        $return_clicent = get_defined_vars();
return $this->view('/lottery/index/edit', $return_clicent);
    }

    /**
     * Desc:修改奖品的各种概率
     * Author:cbw
     * Time: 2023/11/18 14:31
     */
    function editItem()
    {
        global $_G,$_S,$_C,$_P;
        $system = $_S;
        $config = $_C;
        $p_id = intval($_P['p_id']);
        $themeid = $_P['themeid'];
        $where = ['p_id'=>$p_id,'themeid'=>$themeid];
        $data = [];
        $type = isset($_P['type'])?$_P['type']:'pr';
        $msg = '中奖概率';
        $old_item = LotteryModel::getPrizeItemById($p_id,$themeid);

        if ($type=='pr'){
            $old_data['pr'] = $old_item['pr'];
            $data['pr'] = $_P['val'];
        }elseif ($type=='show_pr'){
            $old_data['show_pr'] = $old_item['show_pr'];
            $data['show_pr'] = $_P['val'];
            $type = 'show_pr';
            $msg = '展示记录占比';
        }elseif ($type=='day_qty'){
            $old_data['day_qty'] = $old_item['day_qty'];
            $data['day_qty'] = $_P['val'];
        }
        $res = LotteryModel::editPrizeItemByWhere($where,$data);
        if (!$res){
            show_json(0,['msg'=>'操作失败']);
        }else{
            $type1 = '['.$old_item['title'].']-奖品编辑';
            writelog($themeid,$type1,$old_data,$data,$_G['username']);
            if ($type=='day_qty'){
                show_json(1,['msg'=>'操作成功']);
            }
            $lists = LotteryModel::getPrizeList($themeid,'','',1);
            $is_full_pr = LotteryModel::getPrTotal($lists,$type);
            show_json(1,['msg'=>'操作成功，当前'.$msg.'总和'.$is_full_pr]);
        }
    }

    /**
     * Desc:修改奖品的库存
     * Author:cbw
     * Time: 2023/11/18 14:32
     */
    function editItemQty()
    {
        global $_G,$_S,$_C,$_P;
        $system = $_S;
        $config = $_C;
        $p_id = intval($_P['p_id']);
        $themeid = $_P['themeid'];
        $action = $_P['action'];
        $edit_qty = (int)$_P['qty'];
        $where = ['p_id'=>$p_id,'themeid'=>$themeid];
        $old_item = LotteryModel::getPrizeItemById($p_id,$themeid);
        if ($action=='add'){
            $old_data = ['qty'=>$old_item['qty'],'total_qty'=>$old_item['total_qty']];
            $data = ['qty'=>$edit_qty+$old_item['qty'],'total_qty'=>$edit_qty+$old_item['total_qty']];
            $type1 = '['.$old_item['title'].']-奖品编辑';
            $res = LotteryModel::editPrizeItemByWhere($where,$data);
            writelog($themeid,$type1,$old_data,$data,$_G['username']);
            show_json(1,['msg'=>'操作成功']);
        }else{
            if ($old_item['qty']-$edit_qty<0){
                $data = ['total_qty'=>(int)$old_item['qty']+(int)$old_item['out_qty']];
                $res = LotteryModel::editPrizeItemByWhere($where,$data);
                show_json(0,['msg'=>'减少库存数超过当前可用库存数']);
            }else{
                $old_data = ['qty'=>$old_item['qty'],'total_qty'=>$old_item['total_qty']];
                $data = ['qty'=>max(0,$old_item['qty']-$edit_qty),'total_qty'=>max(0,$old_item['total_qty']-$edit_qty)];
                $type1 = '['.$old_item['title'].']-奖品编辑';
                $res = LotteryModel::editPrizeItemByWhere($where,$data);
                writelog($themeid,$type1,$old_data,$data,$_G['username']);
                show_json(1,['msg'=>'操作成功']);
            }
        }
    }

    /**
     * Desc:更改排序
     * Author:cbw
     * Time: 2023/11/18 14:32
     */
    function editSortItem()
    {
        global $_G,$_S,$_C,$_P;
        $system = $_S;
        $config = $_C;
        $p_id = intval($_P['p_id']);
        $themeid = $_P['themeid'];
        $action = $_P['action'];
        $sort = intval($_P['sort']);
        $temp_sort = 0;

        if ($action=='down'){
            $where = ['p_id'=>$p_id,'themeid'=>$themeid];
            $where1 = ['show_sort'=>$sort+1,'themeid'=>$themeid];
            $data = ['show_sort'=>$temp_sort];
            $data1 = ['show_sort'=>$sort];
            $where2 = ['p_id'=>$p_id,'themeid'=>$themeid];
            $data2 = ['show_sort'=>$sort+1];
        }
        if ($action=='up'){
            $where = ['p_id'=>$p_id,'themeid'=>$themeid];
            $where1 = ['show_sort'=>$sort-1,'themeid'=>$themeid];
            $data = ['show_sort'=>$temp_sort];
            $data1 = ['show_sort'=>$sort];
            $where2 = ['p_id'=>$p_id,'themeid'=>$themeid];
            $data2 = ['show_sort'=>$sort-1];
        }

        $res = LotteryModel::editPrizeItemByWhere($where,$data);
        $res = LotteryModel::editPrizeItemByWhere($where1,$data1);
        $res = LotteryModel::editPrizeItemByWhere($where2,$data2);
        if (!$res || !$res){
            show_json(0,['msg'=>'操作失败']);
        }else{
            show_json(1,['msg'=>'操作成功']);
        }
    }

    /**
     * Desc:格式化奖项类型数据
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2021/3/12 5:49 下午
     * @param $themeid
     * @return array[]
     */
    function getTypeList($themeid,$type='default_type',$_C)
    {
        if ($type=='default_type') {
            $type_list = [
                ['default_type'=>0,'title'=>'全部'],
                ['default_type'=>1,'title'=>'正常奖项'],
                ['default_type'=>2,'title'=>'谢谢参与'],
                ['default_type'=>3,'title'=>'必中奖奖项']
            ];
            foreach ($type_list as $key => $value) {
                if ($value['default_type']==='status'){
                    $list = LotteryModel::getPrizeList($themeid,'','',2,0,0,0);
                }else{
                    $list = LotteryModel::getPrizeList($themeid,'','',0,$value['default_type'],0,0);
                }

                $temp_count = count($list);
                $type_list[$key]['total'] = $temp_count;
            }

        } elseif ($type=='type') {
            $type_list = [
//                ['type'=>'','title'=>'全部'],
                ['type'=>'default','title'=>'实物奖项'],

            ];
            if ($_C['yx_lt_open_red_package']==1){
                array_push($type_list,['type'=>'red_envelope','title'=>'红包奖项']);
            }

            foreach ($type_list as $key => $value) {
                $list = LotteryModel::getPrizeList($themeid,'',$value['type'],0,0,0,0);
                $temp_count = count($list);
                $type_list[$key]['total'] = $temp_count;
            }
        }elseif ($type=='status'){
            $type_list = [
//                ['status'=>0,'title'=>'全部'],
                ['status'=>1,'title'=>'上架'],
                ['status'=>2,'title'=>'下架'],
            ];
            foreach ($type_list as $key => $value) {
                $list = LotteryModel::getPrizeList($themeid,'','',$value['status'],0,0,0);
                $temp_count = count($list);
                $type_list[$key]['total'] = $temp_count;
            }
        }
        return $type_list;
    }

    /**
     * Desc:切换奖品组
     * Author:cbw
     * Time: 2023/11/18 15:30
     * @param $type
     * @return mixed
     */
    function changePrizeGroup($themeid)
    {
        global $_G,$_P,$_S,$_C;
        $themeid = intval($_P['themeid']);
        if($themeid <= 0){
            $themeid = Theme::getDefaultThemenew();
        }
        $lists = LotteryModel::getPrizeList($themeid,'','',0,0,0,0);
        if (count($lists)!=16){
            show_json(0,['msg'=>'奖品数量不足16个无法进行指定操作']);
        }
        //判断最后一个奖品的状态
        $last_prize_item_sql = " select * from ".tablename(yx_lt_prize)." where themeid=$themeid and p_id>0 order by p_id desc limit 1";
        $last_prize_item = db_find($last_prize_item_sql);
        if ($last_prize_item){
            $updated_at = date("Y-m-d H:i:s",time());
            if ($last_prize_item['status']==1){
                //上架前8个  下架后8个
                $sql1 = " update ".tablename(yx_lt_prize)." set status=1,updated_at='$updated_at' order by p_id asc limit 8;".
                    " update ".tablename(yx_lt_prize)." set status=2,updated_at='$updated_at' order by p_id desc limit 8;";
            }elseif ($last_prize_item['status']==2){
                //上架后8个  下架前8个
                $sql1 = " update ".tablename(yx_lt_prize)." set status=1,updated_at='$updated_at' order by p_id desc limit 8;".
                    " update ".tablename(yx_lt_prize)." set status=2,updated_at='$updated_at' order by p_id asc limit 8;";
            }
        }
        $mulit_sql_res = db_run($sql1);
        show_json(1,['msg'=>'切换成功']);
    }
}